<template>
  <a-card :bordered="false" :loading="loading">
    <a-spin :spinning="vloading">
      <a-calendar :defaultValue="showMoment" @panelChange="onPanelChange">
        <!-- <div slot="dateFullCellRender" slot-scope="value"> -->
        <div slot="dateCellRender" slot-scope="value" style="height:100%;">
          
          <!-- <div class="date-wrap" :class="{'noMonth':value.format('MM') !== showMoment.format('MM')}"> -->
            <day-tag
              :dayData="value | dateFilter(workData)"
              :dayValue="value"
              :userId = "userId"
              :showTime = "showMoment"
              @add="handleAddTag"
              @update="handleUpdateTag"
              @del="handleDeleteTag"
              
            ></day-tag>
            <!-- @changeMonth='handleChangeMonth' -->
            <!-- <span class="date-day">{{value.format('DD')}}</span> -->
            <!-- // 0 不上班  1 正常  2上班迟到  3 上班缺卡   4 下班缺卡  5 旷工 -->
          <!-- </div> -->
        </div>
      </a-calendar>
    </a-spin>
    <a-divider orientation="left">出勤统计</a-divider>
    <a-table :columns="attendanceColumns" :data-source="attendanceData" :pagination="false" :rowKey="(list)=>list.id">
      <span slot="date">{{ showMoment ? showMoment.format('YYYY-MM') : '--' }}</span>
    </a-table>
    <a-divider orientation="left">工资条</a-divider>
    <a-table
      ref="table"
      :columns="payColumns"
      :data-source="PayData"
      :rowKey="(list)=>list.id"
      :scroll="{ x: true }"
      :pagination="false"
    >
      <span slot="date">{{ showMoment ? showMoment.format('YYYY-MM') : '--' }}</span>
      <span slot="action">
        <a @click="tabletoExcel">导出</a>
      </span>
      <span slot="tax" slot-scope="text, scope">
        <div v-if="scope.showInput == 'tax'">
          <a-input-number :defaultValue="scope.tax||0" @blur="(e)=>handleEditTable(e, 'tax')" v-action:userPayEdit_update></a-input-number>
        </div>
        <div class="tag-wrap" v-else>
          <span >{{ scope.tax || 0 }}</span>
          <a @click="()=>tableEdit('tax', scope)" v-action:userPayEdit_update>编辑</a>
        </div>
      </span>
      <span slot="projectReward" slot-scope="text, scope">
        <div v-if="scope.showInput == 'projectReward'">
          <a-input-number 
            :defaultValue="scope.projectReward||0" 
            @blur="(e)=>handleEditTable(e, 'projectReward')" 
            v-action:userPayEdit_update
          ></a-input-number>
        </div>
        <div class="tag-wrap" v-else>
          <span >{{ scope.projectReward || 0 }}</span>
          <a @click="()=>tableEdit('projectReward', scope)" v-action:userPayEdit_update>编辑</a>
        </div>
      </span>
      <span slot="fullAttendance" slot-scope="text, scope">
        <div v-if="scope.showInput == 'fullAttendance'">
          <a-input-number 
            :defaultValue="scope.fullAttendance||0" 
            @blur="(e)=>handleEditTable(e, 'fullAttendance')" 
            v-action:userPayEdit_update
          ></a-input-number>
        </div>
        <div class="tag-wrap" v-else>
          <span >{{ scope.fullAttendance || 0 }}</span>
          <a @click="()=>tableEdit('fullAttendance', scope)" v-action:userPayEdit_update>编辑</a>
        </div>
      </span>
      
    </a-table>
    <work-modal
      ref="workModal"
      :visible="work.visible"
      :loading="work.confirmLoading"
      :day="work.day"
      :model="work.mdl"
      @cancel="handleCancel"
      @ok="handleAddTagSave"
    />
  </a-card>
</template>

<script>
import moment from 'moment'
import cloneDeep from 'lodash.clonedeep'
import {
  dingWorkInfo,
  dingWorkInfoBySelf,
  userWorkTagAdd,
  userWorkTagUpdate,
  userPayGetUserPayByDay,
  userPayGetUserPayByDaySelf,
} from '@/api/login'
import { calendar } from 'ant-design-vue'
import DayTag from './DayTag'
import WorkModal from './modal'
import { mapGetters } from 'vuex'
import table2excel from 'js-table2excel'
import { numAdd, numSub } from '@/utils/calulate'
import { userPayEditUpdate } from '@/api/login'
const attendanceColumns = [
  {
    title: '日期',
    dataIndex: 'date',
    width: 120,
    scopedSlots: { customRender: 'date' },
  },
  {
    title: '应出勤天数',

    dataIndex: 'shouldAttendanceDay',
  },
  {
    title: '实际出勤天数',
    dataIndex: 'actualAttendanceDay',
  },
  {
    title: '加班次数',
    dataIndex: 'overtimeNum',
  },
  {
    title: '迟到次数',
    dataIndex: 'lateNum',
  },
  {
    title: '迟到时长(分钟)',
    dataIndex: 'lateTimeLength',
  },
  {
    title: '旷工次数',
    dataIndex: 'absenteeismNum',
  },
  {
    title: '请假次数',
    dataIndex: 'leaveNum',
  },
  {
    title: '缺卡次数',
    dataIndex: 'missCardNum',
  },
  {
    title: '补卡次数',
    dataIndex: 'addCardNum',
  },
]
const payColumns = [
  {
    title: '日期',
    dataIndex: 'date',
    width: 120,
    scopedSlots: { customRender: 'date' },
  },
  {
    title: '姓名',
    dataIndex: 'name',
    width: 120,
  },
  {
    title: '工作室',
    dataIndex: 'studioName',
    width: 120,
    customRender: (text) => text || '--',
  },
  {
    title: '类型',
    dataIndex: 'leixin',
    width: 80,
  },
  {
    title: '基本薪资',
    dataIndex: 'base',
    width: 120,
    customRender: (text) => text || '0',
  },
  {
    title: '绩效薪资',
    dataIndex: 'performance',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '住房补贴',
    dataIndex: 'housing',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '岗位补贴',
    dataIndex: 'quarters',
    width: 100,
    customRender: (text) => text || '0',
  },
  // {
  //   title: '餐费补贴',
  //   dataIndex: 'meal',
  //   width: 100,
  //   customRender: (text) => text || '0',
  // },
  {
    title: '加班补贴',
    dataIndex: 'overtime',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '总薪资',
    dataIndex: 'pay',
    width: 120,
    customRender: (text) => text || '0',
  },
  
  {
    title: '应出勤天数',
    dataIndex: 'shouldAttendance',
    width: 150,
    customRender: (text) => text || '0',
  },
  {
    title: '实际出勤天数',
    dataIndex: 'actualAttendance',
    width: 150,
    customRender: (text) => text || '0',
  },
  
  {
    title: '满勤奖',
    dataIndex: 'fullAttendance',
    width: 100,
    // customRender: (text) => text || '0',
    scopedSlots: { customRender: 'fullAttendance' },
  },
  {
    title: '项目奖金',
    dataIndex: 'projectReward',
    width: 130,
    scopedSlots: { customRender: 'projectReward' },
  },
  {
    title: '加班餐补',
    dataIndex: 'overMeal',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '公积金',
    dataIndex: 'accumulationFund',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '社保',
    dataIndex: 'socialSecurity',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '个税',
    dataIndex: 'tax',
    width: 130,
    scopedSlots: { customRender: 'tax' },
  },
  {
    title: '考勤扣款',
    dataIndex: 'attendanceDeductions',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '银行卡号',
    dataIndex: 'bankCard',
  },
  {
    title: '所属银行',
    dataIndex: 'bankName',
    width: 100,
  },
  {
    title: '实发金额',
    dataIndex: 'actualPay',
    width: 100,
    customRender: (text) => text || '0',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 80,
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  data() {
    return {
      workData: [],
      showMoment: null,
      loading: true,
      vloading:true,
      work: {
        visible: false,
        confirmLoading: false,
        mdl: null,
        day: null,
      },
      attendanceColumns: attendanceColumns,
      attendanceData: [],
      payColumns: payColumns,
      PayData: [],
    }
  },

  components: {
    'a-calendar': calendar,
    DayTag,
    WorkModal
  },
  props: {
    userId: {
      type: Number,
      default: null,
    },
  },
  mounted() {
    this.getWork()
    this.$watch('userId', (n) => {
      if (n) {
        this.getWork()
      } else {
        this.workData = []
      }
    })
  },
  computed: {
    ...mapGetters({ userInfo: 'userInfo' }),
  },
  watch: {},
  methods: {
    tabletoExcel() {
      let column = []
      let datas = cloneDeep(this.PayData)
      let date = this.showMoment.format('YYYY_MM')
      datas[0].date = date
      datas[0].bankCard = datas[0].bankCard.replace(/(\d{4})(?=\d)/g, '$1 ')
      this.payColumns.forEach((v) => {
        if (v.title == '操作') return
        
          let tem = {
            title: v.title,
            key: v.dataIndex,
            type: 'text',
          }
          datas[0][v.dataIndex] = datas[0][v.dataIndex] || 0
          column.push(tem)
      })
      table2excel(column, datas, `${datas[0].name}_${date}`)
      //  table2excel
    },
    // 解析钉钉数据
    analysisDing(a_data) {
      let dataJson = {},
        workData = null
      a_data.works.column_vals.forEach((v) => {
        let id = v.column_vo.id
        dataJson[id] = v.column_vals
      })

      // 0 不上班  1 正常  2上班迟到  3 上班缺卡   4 下班缺卡  5 旷工
      function setValue(i, workIt) {
        if (dataJson[168026911][i].value === '1.0') {
          // 168026911  出勤天数
          workIt.status = 1
        }
        if (dataJson[168026921][i].value === '1') {
          // 168026921  上班缺卡次数
          workIt.status = 3
        }
        if (dataJson[168026922][i].value === '1') {
          // 168026922  下班缺卡次数
          workIt.status = 4
        }
        if (dataJson[168026923][i].value === '1') {
          // 168026923  旷工天数
          workIt.status = 5
        }
        if (dataJson[168026914][i].value === '1') {
          // 168026914  迟到次数
          workIt.status = 2
        }
      }
      workData = dataJson[168026908].map((v, i) => {
        // 168026908  应出勤天数
        let workIt = {
          date: v.date,
          isWork: v.value == '1.0',
          status: -1,
          lateTime: dataJson[168026915][i].value, // 168026915  迟到时长
        }
        if (v.value === '0.0') {
          workIt.status = 0
        }
        setValue(i, workIt)
        return workIt
      })

      a_data.tags.forEach((v) => {
        let i = workData.findIndex((it) => it.date == v.day)
        if (i != -1) {
          workData[i].content ? workData[i].content.push(v) : (workData[i].content = [v])
          if (v.type == 1) {
            workData[i].status = -1
            setValue(i, workData[i])
          } else if (v.type == 2) {
            workData[i].status = 0
          } 
          // else if (v.type == 3) {
          //   workData[i].status = 1
          // }
        }
      })
      return workData
    },
    getWork(a_moment, a_bool) {
      if (!a_bool) {
        this.loading = true
        
      }
      this.vloading = true
      a_moment = a_moment || moment()
      this.showMoment = a_moment
      let startTime = a_moment.startOf('month').format('YYYY-MM-DD'),
        endTime = a_moment.endOf('month').format('YYYY-MM-DD'),
        userId = this.userId
      let data = { startTime, endTime, userId }
      let fun = userId ? dingWorkInfo : dingWorkInfoBySelf
      let payFun = userId ? userPayGetUserPayByDay : userPayGetUserPayByDaySelf
      fun(data)
        .then((res) => {
          let workData = this.analysisDing(res.data)
          this.workData = workData;
          this.vloading = false
        }).catch(err=>{
          this.vloading = false
        })
        .finally(() => {this.loading = false})
      payFun(data)
        .then((res) => {
          res.data.showInput = ''
          res.data.leixin = '工资'
          this.attendanceData = res.data ? [res.data.workAttendanceInfo] : []
          this.PayData = res.data ? [res.data] : []
          this.vloading = false
        }).catch(err=>{
          this.vloading = false
        })
        .finally(() => {this.loading = false})
    },
    onPanelChange(value) {
      this.getWork(value)
    },
    handleAddTag(a_day) {
      this.work.visible = true
      this.work.day = a_day
      this.work.mdl = null
    },
    handleAddTagSave() {
      const form = this.$refs.workModal.form
      this.work.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          values.userId = this.userId
          if (values.id > 0) {
            userWorkTagUpdate(values)
              .then((res) => {
                this.$message.success('操作成功!')
              })
              .finally(() => {
                this.work.visible = false
                this.work.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.getWork(this.showMoment, true)
              })
          } else {
            delete values.id
            userWorkTagAdd(values)
              .then((res) => {
                this.$message.success('操作成功!')
              })
              .finally(() => {
                this.work.visible = false
                this.work.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.getWork(this.showMoment, true)
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeTag(){
      this.getWork(this.showMoment, true)
    },
    handleCancel() {
      this.work.visible = false
      const form = this.$refs.workModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleUpdateTag(a_item, a_day) {
      this.work.visible = true
      this.work.day = a_day
      this.work.mdl = a_item
    },
    handleDeleteTag(a_item, a_day) {
      userWorkTagUpdate({ id: a_item.id, status: -1 }).then((res) => {
        a_item.status = -1
        this.getWork(this.showMoment, true)
        // this.tagChange(a_item, a_day)
      })
    },
    tagChange(a_type, a_item, a_day) {
      let workData = cloneDeep(this.workData)
      console.log(a_item)
      let i = workData.findIndex((v) => v.date.substr(0, 10) == a_day.format('YYYY-MM-DD'))
      if (i != -1 && workData[i].content) {
        let index = workData[i].content.findIndex((v) => v.id == a_item.id)
        if (index != 1) {
          workData[i].content[index].type = a_item.type
          workData[i].content[index].content = a_item.content
          workData[i].content[index].status = a_item.status
        } else {
          workData[i].content.push(a_item)
        }
      }
      console.log(workData)
      this.workData = workData
      // this.$forceUpdate()
    },
    tableEdit(a_str, a_scope){
      a_scope.showInput = a_str
    },
    handleEditTable(e, a_str){
      let val = parseFloat(e.target._value);
      let infoJson = new Object;
      infoJson[a_str] = val
      let data ={
        day: this.showMoment.startOf('month').format('YYYY-MM-DD')+' 00:00:00',
        userId: this.userId,
        infoJson
      }
      userPayEditUpdate(data)
      .then(res=>{
        this.PayData = [{...res.data, ...{showInput: ''}}];
      })
    }
  },
  filters: {
    dateFilter(a_value, a_data = []) {
      let showDate = a_value.format('YYYY-MM-DD') + ' 00:00:00'
      let it = a_data.filter((v) => v.date == showDate)[0] || {}
      return it
    },
  },
  destroyed() {},
}
</script>
<style lang='less' scoped>
/deep/ .ant-fullcalendar-date{
  position: relative;
  .ant-fullcalendar-value{
    position: absolute;
        right: 15px;
    top: 5px;
  }
  .ant-fullcalendar-content{
    // padding-top: 24px;
    box-sizing: border-box;
    height: 100%;
  }
}

.date-wrap {
  // position: relative;
  height: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
  z-index: 1;
  &.noMonth{
    opacity: .2;
  }
  .date-day{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #99999950;
    font-weight: bold;
    font-size: 50px;
    z-index: -1;
  }
}
.tag-wrap{
  display: flex;
  justify-content: space-between;
}
</style>